#include "spritesheetpicture.h"

#include    <stdio.h>
#include    <math.h>
#include    "../common.h"
#include    "../parse/tpjsonreader/tpjsonreader.h"

SpriteSheetPicture::SpriteSheetPicture()
{
    m_sheetTexture = 0;
    m_data.clear();
}

SpriteSheetPicture::~SpriteSheetPicture()
{
    for(unsigned int i = 0; i < m_data.size(); i++)
    {
        delete m_data[i];
    }
    m_data.clear();
}

bool SpriteSheetPicture::loadTexture(const char* fileName)
{
    if(m_sheetTexture != 0)
    {
        printf("picture already load,can't load [%s] any more!\n",fileName);
        return false;
    }

    m_sheetTexture = PersonalTexture::Texture2D::LoadTexture(fileName);

    return m_sheetTexture != 0;
}

bool SpriteSheetPicture::parseJson(const char* jsonFileName)
{
    if(jsonFileName == 0 )
    {
        PERSONAL_DEBUG_LOG(" name is null!");
        return false;
    }

    TPjsonReader jsonReader;
    jsonReader.readjson(jsonFileName);

    unsigned int dataSize = jsonReader.m_data.size();

    if(dataSize == 0)
    {
        PERSONAL_DEBUG_LOG(" json data is null!");
        return false;
    }

    m_data.resize(dataSize);

    for(auto it = jsonReader.m_data.begin(); it != jsonReader.m_data.end(); it++)
    {
        int index = 0;
        std::string pngName = it->first;
        TPjsonReader::Info* info = it->second;
        unsigned int textLen = pngName.length();

        for(int i = 1,result = pngName[textLen - i] - '0'; result >= 0 && result <= 9 ; ++i, result = pngName[textLen - i] - '0')
        {
            index +=  (pow(10,i -1) * result);
        }

        TextureArea* si = new TextureArea();
        si->x = info->x;
        si->y = info->y;
        si->width = info->w;
        si->height = info->h;
        m_data[index - 1] = si;
    }

    setSize(jsonReader.picWidth,jsonReader.picHeight);
    return true;
}

unsigned int SpriteSheetPicture::getNumberOfSheet()const
{
    return m_data.size();
}
const TextureArea* SpriteSheetPicture::getTextureArea(unsigned int index)const
{
    if(index >= m_data.size())
    {
        PERSONAL_DEBUG_LOG(" index out of range!");
        return 0;
    }

    return m_data[index];
}

GLuint SpriteSheetPicture::getTexture()const
{
    return m_sheetTexture;
}
